#!/usr/bin/env bash
set -uo pipefail

#==============================================================#
# File      :   pgbouncer-create-user
# Mtime     :   2020-12-16
# Desc      :   add user to pgbouncer pool
# Path      :   /pg/bin/pgbouncer-create-user
# Copyright (C) 2018-2021 Ruohang Feng
#==============================================================#


#--------------------------------------------------------------#
# Name: pgbouncer-create-user
# Desc: Add or modify pgbouncer userlist
# Arg1: username
# Arg2: password (optional)
# Note: Run this as dbsu (postgres)
#--------------------------------------------------------------#
function pgbouncer-create-user(){
	local username=$1
	local password=${2-''}
	local userlist=${3-'/etc/pgbouncer/userlist.txt'}

	local md5_mon_pass="md5$(echo -n "${password}${username}" | md5sum | awk '{print $1}')"
	local userlist_entry="\"${username}\" \"${md5_mon_pass}\""
	# get md5 password from database if 'auto' is set
	if [[ $password == 'auto' ]]; then
		userlist_entry=$(psql -AXtwq -U postgres -d postgres -c "SELECT concat('\"', usename, '\" \"', passwd, '\"') FROM pg_shadow WHERE usename = '${username}'" 2>/dev/null)
	fi

  echo ${userlist_entry}
	mkdir -p /etc/pgbouncer/
	touch ${userlist}
	if grep -q ${username} ${userlist}; then
		sed -i "/^\"${username}\"[[:blank:]]*.*$/d" ${userlist}
	fi
	echo ${userlist_entry} >> ${userlist}
}

pgbouncer-create-user $@
